package cn.kgc.tangcco.utils.redis;

import cn.hutool.setting.dialect.Props;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @author 李昊哲
 * @Description redis利用jedies编写的工具类
 * @date 2020/12/10 下午2:17
 */
public abstract class BaseJedisUtil {
    private static ThreadLocal<Jedis> t = new ThreadLocal<Jedis>();
    private static Props props = new Props("redis.properties");
    private static String host = props.getProperty("host");
    private static String port = props.getProperty("port");
    private static String password = props.getProperty("password");
    private static String timeout = props.getProperty("timeout");
    private static String maxTotal = props.getProperty("maxTotal");
    private static String database = props.getProperty("database");
    private static JedisPool jedisPool = null;

    /**
     * 获取redis客户端 Jedis对象
     *
     * @return
     */
    public static Jedis getClient() {
        if (t.get() != null) {
            return t.get();
        }
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMaxTotal(Integer.parseInt(maxTotal));
        jedisPool = new JedisPool(config, host, Integer.parseInt(port), Integer.parseInt(timeout), password, Integer.parseInt(database));
        Jedis jedis = jedisPool.getResource();
        t.set(jedis);
        return jedis;
    }

    public static Jedis getClient(int database) {
        if (t.get() != null) {
            return t.get();
        }
        if (database < 0) {
            database = 0;
        } else if (database > 15) {
            database = 15;
        }
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMaxTotal(Integer.parseInt(maxTotal));
        jedisPool = new JedisPool(config, host, Integer.parseInt(port), Integer.parseInt(timeout), password, database);
        Jedis jedis = jedisPool.getResource();
        t.set(jedis);
        return jedis;
    }

    /**
     * 释放资源
     */
    public static void close() {
        getClient().close();
    }

    /**
     * 释放资源
     *
     * @param database
     */
    public static void close(int database) {
        getClient(database).close();
    }
}
